<template>
  <div>
    <!-- 主界面的内容 -->
    <!-- 绑定邮箱的弹窗 -->
    <el-dialog :visible.sync="bindingDialogVisible" title="绑定邮箱" width="400px">
      <el-form ref="bindingForm" :model="bindingForm" :rules="bindingRules">
        <el-form-item prop="email">
          <el-input v-model="bindingForm.email" type="text" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="passwordHash">
          <el-input v-model="bindingForm.passwordHash" :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="bindEmailPassword">绑定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { bindEmailApi } from '@/api/login'; // 假设您已实现了 loginApi 方法

export default {
  data() {
    return {
      bindingDialogVisible: false,
      bindingForm: {
        email: '',
        passwordHash: '',
      },
      showPassword: false,
    };
  },
  computed: {
    bindingRules() {
      const validateEmail = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入邮箱'));
        } else {
          callback();
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码必须在6位以上'));
        } else {
          callback();
        }
      };
      return {
        email: [{ validator: validateEmail, trigger: 'blur' }],
        passwordHash: [{ validator: validatePassword, trigger: 'blur' }],
      };
    },
  },
  mounted() {
    // 检查是否需要绑定邮箱
    if (localStorage.getItem('requiresBinding')) {
      this.bindingDialogVisible = true; // 显示绑定对话框
      localStorage.removeItem('requiresBinding'); // 移除标记
    }
  },
  methods: {
    async bindEmailPassword() {
      this.$refs.bindingForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await bindEmailApi({
              email: this.bindingForm.email,
              passwordHash: this.bindingForm.passwordHash,
            });
            if (response && response.code === 200) {
              this.$message.success('绑定成功');
              this.bindingDialogVisible = false; // 关闭对话框
            } else {
              this.$message.error(response.msg || '绑定失败');
            }
          } catch (error) {
            this.$message.error('绑定过程中发生错误');
          }
        }
      });
    },
    handleSomeAction() {
      // 这里是主界面中某些操作的逻辑
    },
    togglePassword() {
      this.showPassword = !this.showPassword;
    },
  },
};
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>
